// JavaScript Document
// Ajax request to update the location (province, district, commune and village)
$(document).ready(function (){
	
    //start update those elements
    requestUpdateProvince($('#province'));
	
    $("#province").change(function(){
        requestUpdateDistrict($("#district"), $("#commune"), $("#village"), $(this).val());
    }); 
	
    $("#district").change(function(){
        requestUpdateCommune($("#commune"), $("#village"), $(this).val());	
    }); 
	
    $("#commune").change(function(){
        requestUpdateVillage($("#village"), $(this).val());	
    });
});


function requestUpdateProvince(provinceEle){
    $(provinceEle).load('/webits-msms/index.php/location/get_province', function(){
        $(provinceEle).trigger("liszt:updated");
    });
}
	
//get new district item when user changes province
function requestUpdateDistrict(districtEle, commnuneEle, villageEle, provinceId){
    $(districtEle).load('/webits-msms/index.php/location/get_district?provid='+provinceId, function(){
        $(districtEle).trigger("liszt:updated");
        $(commnuneEle).find('option').remove().end().append('<option value="">ឃុំ</option>').val('').trigger("liszt:updated");
        $(villageEle).find('option').remove().end().append('<option value="">ភូមិ</option>').val('').trigger("liszt:updated");
    });
}
	
//get new commune items when user changes district
function requestUpdateCommune(commnuneEle, villageEle, districtId){
    $(commnuneEle).load('/webits-msms/index.php/location/get_commune?distid='+districtId, function(){
        $(commnuneEle).trigger("liszt:updated");
        $(villageEle).find('option').remove().end().append('<option value="">ភូមិ</option>').val('').trigger("liszt:updated");
    });
}
	
//get new village items when user changes commune
function requestUpdateVillage(villageEle, communeId){
    $(villageEle).load('/webits-msms/index.php/location/get_village?commid='+communeId, function(){
        $(villageEle).trigger("liszt:updated");
    });
}